<template>
  <div class="quick-filter relative flex"
       v-loading="disabledId  || loading">
    <slot name="crumb"
          v-if="$slots.crumb"></slot>
    <QuickFilterItem v-for="(record) in baseOptionsData"
                     :key="record.id"
                     :name="record.name"
                     :active="record.id===value.id"
                     :total = "record.total"
                     :isShowTotal="isShowTotal"
                     suffix-icon="el-icon-close"
                     :close="record.close"
                     @click.native="handleClick(record)">

      <template v-slot:suffix>
        <img src="@/assets/img/dismiss.png"
             @click.stop="handleDeleteQuickFilter(record)">

      </template>
    </QuickFilterItem>

    <scroll-pane :class="['quick-filter__dl','flex','flex-nowrap']"
                 :style="{
                   width:options.length ? 'auto':'1px',
                   marginRight:options.length ? '16px':0
                 }"
                 ref="quick-filter-dl">
      <QuickFilterItem v-for="(record) in options"
                       :key="record.id"
                       :name="record.name"
                       :active="record.id===value.id"
                       :total = "record.total"
                       :isShowTotal="isShowTotal"
                       suffix-icon="el-icon-close"
                       :close="record.close"
                       @click.native="handleClick(record)">
        <template v-slot:suffix>
          <img src="@/assets/img/dismiss.png"
               @click.stop="handleDeleteQuickFilter(record)">

        </template>
      </QuickFilterItem>

    </scroll-pane>
    <AddQuickFilter @event:add="$emit('event:add',options)" />
  </div>
</template>

<script>
import QuickFilterItem from './quick-filter-item'
import QuickFilterSearch from './quick-filter-search'
import QuickFilterTooltip from './quick-filter-tooltip'
import AddQuickFilter from './add-quick-filter'
import ScrollPane from './scroll-pane'

export default {
  name: 'QuickFilter',
  components: {
    QuickFilterItem,
    QuickFilterSearch,
    QuickFilterTooltip,
    AddQuickFilter,
    ScrollPane
  },
  inject: {
    addWidgetSearchForm: {
      default: false
    }
  },
  props: {
    type: {
      type: String,
      require: true
    },
    value: {
      type: Object,
      default: () => ({})
    },
    callback: {
      type: Function
    },
    immediate: {
      type: Boolean,
      default: false
    },
    isInternal: {
      type: Boolean,
      default: false
    },
    baseOptions: {
      type: Array,
      default: () => ([])
    },
    loading: {
      type: false,
      default: false
    }

  },
  data () {
    return {
      options: [],
      cloneOptions: [],
      disabledId: undefined,
      baseOptionPath: ['/Dashboards', '/Widgets', '/Scorecards', '/Slicer'],
      baseOptionsData: this.baseOptions,
      isShowTotal: false,
      activatedFlag: false
    }
  },
  watch: {
    '$store.state.refreshQuickFilter': function (value, oldValue) {
      if (this.activatedFlag) {
        this.getQuickFilters('integration')
      }
    }
  },
  async created () {
    await this.getQuickFilters()
  },
  activated () {
    this.$root.eventBus.$on('bus:close', this.refresh)
    this.$root.eventBus.$on('bus:route-complete', (query) => {
      this.$emit('event:route-complete', query)
    })
    this.$root.eventBus.$on('addRemoveFavorite', (params) => {
      // this.getQuickFilters()
      let favorite = this.baseOptionsData[0]
      if (params === 'remove') {
        favorite.total = favorite.total - 1
        if (favorite.total < 0) {
          favorite.total = 0
        }
      } else {
        favorite.total = favorite.total + 1
      }
      this.$set(this.baseOptionsData, 0, favorite)
    })
    this.activatedFlag = true
  },

  deactivated () {
    this.$root.eventBus.$off('bus:close')
    this.$root.eventBus.$off('bus:route-complete')
    this.$root.eventBus.$off('addRemoveFavorite')
    this.activatedFlag = false
  },

  methods: {
    getRequestType (type) {
      let urlType = null
      switch (type) {
        case 'slicer':
        case 'widget' :
          urlType = 'model'
          break
        case 'report' :
        case 'scorecard-report':
          urlType = 'report'
          break
        case 'bot':
          urlType = 'bot'
          break
        default:
          urlType = 'model'
      }
      return urlType
    },
    getAddWidgetType () {
      if (!this.addWidgetSearchForm) {
        return false
      }
      const tag = this.addWidgetSearchForm.selectedWidgetPane || ''
      let type = null
      switch (tag) {
        case 'published' :
          type = 'widget'
          break
        case 'publishedslicer' :
          type = 'slicer'
          break
        default:
          type = null
      }
      return type
    },
    async getQuickFilters (integration) {
      try {
        this.$emit('update:loading', true)
        const { type } = this
        const { quickFilters, quickFiltersTotal } = this.$interface.reports
        const { get, findIndex, concat } = this._

        const params = {
          type: this.getAddWidgetType() || type
        }
        if (this.$store.state.REFRESHCACHE) {
          params.queryType = 'REFRESHCACHE'
          this.$store.state.REFRESHCACHE = false
        }
        const mode = this.getAddWidgetType() || type
        if (this.isInternal && mode === 'widget') {
          params.type = 'internal-widget'
          params.businessType = ['MSPbots Internal']
        }
        if (this.isInternal && mode === 'slicer') {
          params.type = 'internal-slicer'
          params.businessType = ['MSPbots Internal']
        }
        if (!this.isInternal && mode === 'slicer') {
          params.type = 'slicer'
          params.businessType = ['Custom', 'Template']
        }
        if (!this.isInternal && mode === 'widget') {
          params.type = 'widget'
          params.businessType = ['Custom', 'Template']
        }

        if (this.baseOptionPath.includes(this.$route.path) || this.getAddWidgetType()) {
          const { data: response } = await quickFiltersTotal(params, this.getRequestType(this.getAddWidgetType() || type))
          if (response.code !== 0) {
            throw get(response, 'msg', '')
          }

          this.cloneOptions = get(response, 'data', [])
          this.isShowTotal = true
          const arr = this.cloneOptions.slice(0, 3)
          this.cloneOptions.splice(0, 3)
          this.baseOptionsData = this.baseOptionsData.map((item, index) => {
            item.total = arr[index].total ? arr[index].total : 0
            return item
          })
          this.cloneOptions.map(item => {
            if (item.filterJson.filter.subLevelType && item.filterJson.filter.subLevelType === 100101) {
              item.filterJson.filter.type.push('Community')
            }
            return item
          })
          this.options = this.cloneOptions
          const handleArr = concat(this.baseOptionsData, this.cloneOptions)
          const index = findIndex(handleArr, (item) => {
            return item.total && item.total > 0
          })
          if (index !== -1 && !integration) {
            return await this.handleClick(handleArr[index])
          }
          if (this.immediate) {
            this.$emit('event:change', this.getCurrentValue(this.value))
          }
        } else {
          const { data: response } = await quickFilters(params)
          if (response.code !== 0) {
            throw get(response, 'msg', '')
          }

          this.cloneOptions = get(response, 'data', [])
          this.options = this.cloneOptions

          if (this.immediate) {
            this.$emit('event:change', this.getCurrentValue(this.value))
          }
        }
      } catch (error) {

      } finally {
        this.$emit('update:loading', false)
      }
    },
    handleDeleteQuickFilter (record) {
      this.$confirm(this.$t('prompt.info', { 'handle': this.$t('delete') }), this.$t('prompt.title'), {
        confirmButtonText: this.$t('confirm'),
        cancelButtonText: this.$t('cancel'),
        type: 'warning'
      }).then(async () => {
        const { get, nth } = this._
        try {
          this.disabledId = record.id
          const { id } = record
          const { deleteQuickFilter } = this.$interface.reports

          const { data: response } = await deleteQuickFilter(id)
          if (response.code !== 0) {
            throw get(response, 'msg', '')
          }

          await this.refresh()
          if (this.baseOptionsData.length > 0) {
            this.handleClick(nth(this.baseOptionsData, 0))
          }
        } catch (error) {
          if (typeof error === 'string') {
            this.$message.error(error)
          }
        } finally {
          this.disabledId = undefined
        }
      })
    },
    getCurrentValue (record) {
      const findVal = [...this.options, ...this.baseOptionsData].find(i => i.id === record.id)
      return findVal
    },
    async handleClick (record) {
      this.$emit('input', this.getCurrentValue(record))
      this.$emit('event:change', this.getCurrentValue(record))
    },
    async refresh () {
      await this.getQuickFilters()
    }

  }
}
</script>

<style lang="scss" scoped>
.quick-filter {
  padding: 16px 16px 0 0;
  box-shadow: inset 0px -1px 0px 0px #f0f0f0;
  &__dl {
    height: 40px;
  }
}
</style>
